/* 
    搜索页面

    1.联想建议
    2.搜索历史      =>点击都会跳转
    3.搜索内容

 */
<template>
    <div class="searchMain">
        <!-- 搜索栏 -->
        <form action="/" class="searchForm">
            <van-search v-model="searchText" show-action placeholder="请输入搜索关键词" @search="onSearch" @cancel="onCancel"
                background="#3296fa" @focus="onFocus" />
        </form>

        <!-- 搜索结果-->
        <SearchResult v-if="isResultShow" search-text="searchText" />

        <!-- 联想建议 -->
        <SearchSuggestion v-else-if="searchText" search-text="searchText" @search="onSearch" />

        <!-- 搜索历史 -->
        <SearchHistory v-else :searchHistories="searchHistories" @clearSearchHistories="searchHistories = []"
            @search="onSearch" />
    </div>
</template>

<script>
import SearchHistory from './components/searchHistory'
import SearchResult from './components/searchResult'
import SearchSuggestion from './components/searchSuggestion'
import { setItem, getItem } from '@/utils/storage'

export default {
    name: 'Search',
    data() {
        return {
            searchText: '',
            isResultShow: false,//控制搜索结果展示
            searchHistories: getItem('searchHistories') || [],//搜索历史
        }
    },
    created() {

    },
    components: {
        SearchHistory, SearchResult, SearchSuggestion
    },
    watch: {
        searchHistories(value) {
            setItem('searchHistories', value)
        }
    },
    methods: {
        onSearch(val) {
            // 更新文本框内容
            this.searchText = val

            // 存储搜索记录
            /*  
                1.要求不要有重复历史记录
                2.最新的排在最前面
            */
            const index = this.searchHistories.indexOf(val)
            if (index !== -1) {
                this.searchHistories.slice(index, 1)
            }
            this.searchHistories.unshift(val)

            // 展示渲染结果
            this.isResultShow = true
        },
        onFocus() {
            this.isResultShow = false
        },
        onCancel() {
            this.$router.back()
        },
    }
}
</script>

<style scoped lang="less">
.searchMain {
    width: 100%;
    height: 100%;
    padding-top: 54px;

    /deep/ .searchForm {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 999;
    }
}
</style>